# -*- coding: utf8 -*-
import mechanize
from bs4 import BeautifulSoup
import os

class TeacherHelper(object):

    #global instance of DBop

    @staticmethod
    #def instance(self,redisHost={'host':'127.0.0.1','port':6379,'db':0}):
    def instance():
        """Returns a global `feed` instance."""

        if not hasattr(TeacherHelper, "_instance"):
            TeacherHelper._instance = TeacherHelper()

        return TeacherHelper._instance


    def __init__(self):

        self.browser = mechanize.Browser()
        self.isLogin = False
        self.fileListUrl = ''
        self.finfos = []
        self.Uri = ''
        pass

    def init(self,loginUrl,user,pwd):
        self.loginUrl = loginUrl
        self.delUrl = loginUrl + '/deletefile.ashx?wenjianid='
        self.user = user
        self.pwd = pwd

    def login(self):
        #option
        self.browser.set_handle_equiv(True)
        self.browser.set_handle_gzip(True)
        self.browser.set_handle_redirect(True)
        self.browser.set_handle_referer(True)
        self.browser.set_handle_robots(False)
        self.browser.addheaders = [('User-agent','Mozilla/X.0(Firefox/X.X)')]

        response = self.browser.open(self.loginUrl)
        html = response.read()
        self.browser.select_form(nr=0)
        self.browser.form["TextBox1"] = self.user
        self.browser.form["TextBox2"] = self.pwd
        self.browser.submit()

        html = self.browser.response().read()
        if 'xiugeimima' in html:
            print 'login success ...'
            self.isLogin = True
            self.fileListUrl = self.browser.geturl()
        else:
            print 'login failed ...'
            self.isLogin = False
        return self.isLogin

    def getHtml(self):
        pass

    def getFileList(self):
        if len(self.fileListUrl) == 0:
            self.login()
            if not self.isLogin:
                return []
        response = self.browser.open(self.fileListUrl)
        html = response.read()
        #print html
        soup = BeautifulSoup(html, 'html.parser')
        files = soup.find_all('div','tile-content')
        for f in files:
            h5s = f.find_all('h5')
            p = f.find('p')
            fname = h5s[0].text
            ftime = '20' + h5s[1].text.split("20")[1]
            fauther = p.text
            self.finfos.append([fname,ftime,fauther])

        hrefs = soup.find_all('a',text=u"删除")
        if len(hrefs) != len(self.finfos) :
            print "Error: the num of files not equal to file ids"
            return
        for i in range(0,len(hrefs)):
            h = hrefs[i].get('href')
            if 'wenjianid=' in h :
                fid = h.split('=')[1]
                self.finfos[i].append(fid)

        for finfo in self.finfos:
            print finfo[0],finfo[1],finfo[2],finfo[3]

        return self.finfos

    def deleteFile(self,fileId):
        url = domain + '/deletefile.ashx?wenjianid=' + fileId
        pass

    def uploadFile(self,fileName):
        baseName = os.path.basename(fileName)
        self.browser.select_form(nr=0)
        self.browser.form.set_value(["2"], name="DropDownList1", kind="list")
        self.browser.form["TextBox1"] = baseName
        self.browser.add_file(open(fileName),'application/octet-stream',baseName)
        self.browser.submit()
        print self.browser.response().read()


        pass

if __name__ == "__main__":
    url = 'http://192.168.120.114:2017'
    tHelper = TeacherHelper()
    user = '2013111004'
    pwd = 'lightning123'
    tHelper.init(url,user,pwd)
    #path = '/opt/autoTeacher/doHttp.doc'
    #tHelper.uploadFile(path)

    files = tHelper.getFileList()
    for f in files:
        print f
